package io.gitee.yth.design.pattern.test.core.pattern.behavioral.observer;

import java.util.Objects;

/**
 * 具体观察者
 *
 * @author yth
 * @since 2023-04-30-15:38
 */
public class DigitClock implements IObserver {

    private ClockTimer clockTimer;

    public DigitClock(ClockTimer clockTimer) {
        bind(clockTimer);
    }

    /**
     * 绑定目标
     */
    public void bind(ClockTimer clockTimer) {
        Objects.requireNonNull(clockTimer);
        unbind();
        this.clockTimer = clockTimer;
        this.clockTimer.attach(this);
    }

    /**
     * 解除绑定
     */
    public void unbind() {
        if (clockTimer != null) {
            clockTimer.detach(this);
        }
    }

    /**
     * 重写具体更新逻辑
     *
     * @param theChangedSubject 更新的数据
     */
    @Override
    public void update(ISubject theChangedSubject) {
        Objects.requireNonNull(theChangedSubject);
        if (theChangedSubject == clockTimer) {
            redrawTime();
        }
    }

    private void redrawTime() {
        System.out.println("update >> latest time: " + clockTimer);
    }

    @Override
    protected void finalize() throws Throwable {
        unbind();   // 防止弱引用、软引用等的使用，导致内存泄露
    }
}
